<template>
  <div class="class-create-root">

    <!-- @closed 窗口关闭时结束时的回调   -->
    <el-drawer v-model="interviewStore.interviewStoreDialogVisible" :title="ruleForm.title" size="600"
               @closed="toggleDialog"
               style="text-align: center;font-weight:bold;"
    >

      <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <el-form-item label="学员姓名" prop="student_id">
          <el-select v-model="ruleForm.student_id" placeholder="请选择学员">
            <el-option v-for="item in studentList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="面试时间" required>
          <el-col :span="11">
            <el-form-item prop="date">
              <el-date-picker
                  v-model="ruleForm.date"
                  type="date"
                  aria-label="Pick a date"
                  placeholder="选择一个日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col class="text-center" :span="2">
            <span class="text-gray-500">-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="time">
              <el-time-picker
                  v-model="ruleForm.time"
                  aria-label="Pick a time"
                  placeholder="选择一个时间"
                  style="width: 100%"
                  value-format="HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="面试类型" prop="interview_type">
          <el-radio-group v-model="ruleForm.interview_type">
            <el-radio v-for="(value,key) in INTERVIEW_TYPE":key="key" :value="key">{{value}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="面试公司" prop="company_name">
          <el-input v-model="ruleForm.company_name" />
        </el-form-item>
        <el-form-item label="所在城市" prop="work_location">
          <AreaSelect v-model="ruleForm.work_location"/>
        </el-form-item>
        <el-form-item label="面试轮次" prop="interview_rounds">
          <el-select-v2
              v-model="ruleForm.interview_rounds"
              placeholder="请选择面试轮次"
              :options="options"
          />
        </el-form-item>
        <el-form-item label="面试结果" prop="interview_result">
          <el-radio-group v-model="ruleForm.interview_result">
            <el-radio v-for="(value,key) in interviewResultOptions" :label="value" :key="key" :value="key">{{ value }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="面试录音" prop="interview_record">
          <el-upload
              ref="ruleForm.interview_record"
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :on-change="handleChange"
              :limit="1"
              :auto-upload="false"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref,} from 'vue'
import { useInterviewStore } from "@/store/store-interview";
import { useSysDictStore } from "@/store/store-sys-dict-pinia"
import { SYS_DICT } from "@/dict/dict-sys";
import {getEmployeesByPortAPI} from "@/network/employee/employee";
import EventBus from "@/plugins/event-bus"
import {addStudentInterviewAPI, updateStudentInterviewAPI} from "@/network/interview/interview";
import {ElMessage} from "element-plus";
import {uploadFileAPI} from "@/network/upload-file";
import AreaSelect from "@/components/common/AreaSelect.vue";
import {INTERVIEW_TYPE, INTERVIEW_ACTION} from "@/dict/dict-interview"

let studentList = ref();
const interviewStore = useInterviewStore();
const sysDictStore = useSysDictStore();
const toggleDialog = () => {
  interviewStore.toggleInterviewStoreDialogVisible();
};
// 监听学生列表改变
EventBus.on("student-list-event", (data) => {
  studentList.value = data;
})
// 监听新增窗口打开事件
EventBus.on("add-interview-data-event", (addInterviewData) => {
  ruleForm.action_type = addInterviewData.actionType;
  ruleForm.className  = addInterviewData.className
  ruleForm.title = addInterviewData.className + "面试记录录入"
})

EventBus.on("update-interview-data-event",(updateInterviewData)=>{
  console.log(updateInterviewData)
  // 面试信息id，更新需要传这个数据
  ruleForm.id = updateInterviewData.id;
  ruleForm.student_id = updateInterviewData.student_id;
  ruleForm.interview_type = Object.keys(INTERVIEW_TYPE).find(key => INTERVIEW_TYPE[key] === updateInterviewData.interview_type);
  ruleForm.company_name = updateInterviewData.company_name;
  ruleForm.date = updateInterviewData.interview_time.split(" ")[0];
  ruleForm.time = updateInterviewData.interview_time.split(" ")[1]+":00";
  ruleForm.work_location = updateInterviewData.work_location;
  ruleForm.interview_rounds = updateInterviewData.interview_rounds;
  ruleForm.interview_result = Object.keys(interviewResultOptions).find(key => interviewResultOptions[key] === updateInterviewData.interview_result);
  ruleForm.interview_record = updateInterviewData.interview_record;
  ruleForm.action_type = updateInterviewData.actionType;
  ruleForm.className  = updateInterviewData.className
  ruleForm.title = studentList.value.filter(item => item.id === updateInterviewData.student_id).map(item => item.name) + "面试记录更新"

})
/*
{
  "student_id": 1,
  "interview_type": 1,
  "company_name": "法本信息",
  "work_location": "深圳",
  "interview_time": "2024-10-05T09:26:50.273Z",
  "interview_rounds": 1,
  "interview_result": 0,
  "interview_record": "interview-record-url",
  "lecturer_id": 1,
  "lecturer_comment": "面试不错继续加油"
}
* */
// 取面试结果的字典
sysDictStore.getSysDict([SYS_DICT.INTERVIEW_RESULT])
let interviewResultOptions = sysDictStore.INTERVIEW_RESULT
console.log(interviewResultOptions)
// 下边是具体处理表格中数据的逻辑
const formSize = ref('default')
const ruleFormRef = ref()
const ruleForm = reactive({
  company_name: '',
  student_id: '',
  interview_rounds: '',
  date: '',
  time: '',
  interview_result: '',
  interview_type: '',
  work_location:'',
  interview_record: '',
})

const rules = reactive({
  company_name: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
  ],
  work_location: [
    { required: true, message: '请输入工作地点', trigger: 'blur' },
  ],
  student_id: [
    {
      required: true,
      message: '请选择一个学员',
      trigger: 'change',
    },
  ],
  interview_rounds: [
    {
      required: true,
      message: '请输入面试轮次',
      trigger: 'change',
    },
  ],
  date: [
    {
      type: 'date',
      required: true,
      message: '请选择面试日期',
      trigger: 'change',
    },
  ],
  time: [
    {
      type: 'time',
      required: true,
      message: '请选择面试时间',
      trigger: 'change',
    },
  ],
  interview_result: [
    {
      required: true,
      message: '请选择面试结果',
      trigger: 'change',
    },
  ],
  interview_type: [
    {
      required: true,
      message: '请选择面试类型',
      trigger: 'change',
    },
  ],
})

// 文件选择时触发
const handleChange = (file) => {
  // console.log('文件选择时触发', file);
  ruleForm.interview_record = file
};

const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.interview_time = ruleForm.date + " " + ruleForm.time
      let requestData = {
        "student_id": ruleForm.student_id,
        "interview_type": ruleForm.interview_type,
        "company_name": ruleForm.company_name,
        "work_location": ruleForm.work_location,
        "interview_time": ruleForm.interview_time,
        "interview_rounds": ruleForm.interview_rounds,
        "interview_result": ruleForm.interview_result,
        "interview_record": ruleForm.interview_record ? ruleForm.interview_record : "",
      }
      console.log(requestData)
      // 如果操作的动作是添加面试记录的逻辑
      if(ruleForm.action_type === INTERVIEW_ACTION.ADD){
      //  判断是否上传了文件
          if(requestData.interview_record == ""){
            addStudentInterviewData(requestData)
          }else{
            const formData = new FormData();
            formData.append('file', requestData.interview_record.raw, requestData.interview_record.name);
            uploadFileAPI(formData,"record").then((res)=>{
              // console.log(res)
              requestData.interview_record = res.data.data.url
              addStudentInterviewData(requestData)
            })
          }
        //  如果操作的动作是更新则走下边的逻辑
        }else if (ruleForm.action_type === INTERVIEW_ACTION.UPDATE){
            requestData.id = ruleForm.id; //  添加面试记录id
            updateStudentInterviewAPI(requestData).then((res)=>{
                if(res.data.code!=0){
                  ElMessage.error(res.data.message)
                }else{
                  ElMessage.success(res.data.message);
                  //  成功以后清空表单
                  formEl.resetFields()
                }
            })
        }

      } else {
      console.log('提交失败', fields)
    }
  })
}
// 添加学员面试记录请求
const addStudentInterviewData = ()=>{
  addStudentInterviewAPI(requestData).then((res)=>{
    if(res.data.code!=0){
      ElMessage.error(res.data.message)
    }else{
      ElMessage.success(res.data.message);
      //  成功以后清空表单
      formEl.resetFields()
    }
  })
}


const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}))

</script>

<style scoped lang="less">
.class-create-root {
}
</style>